package org.yaac.client.activity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.inject.Inject;

import org.yaac.client.place.BlobPlace;
import org.yaac.client.service.BlobServiceAsync;
import org.yaac.client.ui.BlobView;
import org.yaac.client.util.ExceptionManager;
import org.yaac.client.widget.BlockingAsyncCallback;
import org.yaac.shared.blob.BlobInfoDTO;

import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

/**
 * @author Max Zhu (thebbsky@gmail.com)
 *
 */
public class BlobActivity extends SinglePlaceActivity<BlobPlace> {

	private final BlobView view;
	
	private final BlobServiceAsync blobService;
	
	private final ExceptionManager exceptionManager;
	
	/**
	 * @param view
	 */
	@Inject
	BlobActivity(BlobView view, BlobServiceAsync blobService, ExceptionManager exceptionManager) {
		super();
		this.view = view;
		this.blobService = blobService;
		this.exceptionManager = exceptionManager;
	}

	@Override
	public SinglePlaceActivity<BlobPlace> withPlace(BlobPlace place) {
		return this;
	}
	
	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		view.setPresenter(this);
		containerWidget.setWidget(view.asWidget());
		
		refreshBlobInfo();
	}

	public void refreshBlobInfo() {
		String filterStr = view.filterStr();
		
		blobService.load(filterStr, new BlockingAsyncCallback<List<BlobInfoDTO>>() {
			@Override
			public void onBlockingCallSuccess(List<BlobInfoDTO> result) {				
				view.updateBlobInfoList(result);
			}

			@Override
			public void onBlockingCallFailure(Throwable caught) {
				exceptionManager.handle(caught);
			}
		});
	}

	public void delete(Collection<BlobInfoDTO> selectedBlobs) {
		Collection<String> blobKeys = Collections2.transform(selectedBlobs, new Function<BlobInfoDTO, String>() {
			@Override
			public String apply(BlobInfoDTO input) {
				return input.getBlobKeyStr();
			}
		});
		
		blobService.delete(
				new ArrayList<String>(blobKeys),	// original string is not serializable 
				new BlockingAsyncCallback<Void>() {

			@Override
			public void onBlockingCallSuccess(Void result) {
				refreshBlobInfo();
			}

			@Override
			public void onBlockingCallFailure(Throwable caught) {
				exceptionManager.handle(caught);
			}
		});
	}
}
